const express = require("express");
const bodyParser = require("body-parser");
const { readFileSync, writeFileSync } = require("fs");
const { setTargetTypeLang } = require("./libs/utils");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const prefix = "/api";

app.all("*", (req, res, next) => {
  // res.setHeader('Access-Control-Allow-Origin','*');
  res.setHeader("Content-Type", "application/json");
  next();
});

app.get(`${prefix}/get-langs-data`, (req, res) => {
  const totalLangs = JSON.parse(readFileSync("./lang/langs.json") || "[]");

  const zhCN = setTargetTypeLang(totalLangs, "zh-CN"),
    zhXG = setTargetTypeLang(totalLangs, "zh-XG"),
    en = setTargetTypeLang(totalLangs, "en");

  const langs = {
    /* directly import */
    // "zh-CN": JSON.parse(readFileSync("./lang/zh-CN.json") || "{}"),
    // "zh-XG": JSON.parse(readFileSync("./lang/zh-XG.json") || "{}"),
    // en: JSON.parse(readFileSync("./lang/en.json") || "{}"),

    /* langs-data */
    "zh-CN": zhCN,
    "zh-XG": zhXG,
    en,
  };

  res.send(langs);
});

app.post(`${prefix}/set-langs-data`, (req, res) => {
  const totalLangs = JSON.parse(readFileSync("./lang/langs.json") || "[]");

  const { type, data } = req.body;

  if (!type) {
    res.send({
      code: 700,
      status: "Error",
      msg: "请填写需要修改的语言类型",
    });
  }
  if (!["zh-CN", "zh-XG", "en", "all"].includes(type)) {
    res.send({
      code: 404,
      msg: "当前语言不存在",
    });
    return;
  }
  if (!Array.isArray(data)) {
    res.send({
      code: 700,
      msg: "语言信息需为数组",
    });
  }
  if (!data.length) {
    res.send({
      code: 700,
      msg: "语言内容不得为空",
    });
  }
  if (type === "all") {
    data.forEach((newData) => {
      const repeatIndex = totalLangs.findIndex(
        (oldData) =>
          oldData.module === newData.module &&
          oldData.sentence === newData.sentence
      );
      if (repeatIndex > -1) {
        totalLangs.splice(repeatIndex, 1);
      }
      totalLangs.unshift(newData);
    });
  } else {
    // todo
  }

  writeFileSync("./lang/langs.json", JSON.stringify(totalLangs));

  res.send({
    code: 0,
    msg: "修改成功",
  });
});

app.listen(4000, () => {
  console.log("app running at port:4000");
});
